/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package LwuitUI;

/**
 *
 * @author anup.s
 */
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.List;
import com.sun.lwuit.Label;
import com.sun.lwuit.list.ListCellRenderer;
import com.sun.lwuit.Image;
import com.sun.lwuit.Graphics;
import com.sun.lwuit.RGBImage;
import com.sun.lwuit.layouts.*;
import com.sun.lwuit.plaf.*;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.events.FocusListener;

import mujmail.TheBox;
import mujmail.IStorage;
import mujmail.MessageHeader;
import java.util.Vector;
import java.util.Enumeration;

import mujmail.Settings;
import mujmail.account.MailAccount;
import mujmail.Lang;
import mujmail.util.Functions;
import com.sun.lwuit.events.SelectionListener;
import com.sun.lwuit.plaf.UIManager;

public class BoxRenderer extends Container implements ListCellRenderer, SelectionListener {

    private Label icon = new Label("");
    private Label from = new Label("");
    private Label sub = new Label("");
    private Label date = new Label("");
    Image imNormal, imDeleted, imRead, imAnswered, imSent, imFailedSent, imAttch, imFlagged, imRoot;
    List mailList;
    TheBox box;
    private static final boolean DEBUG = false;

    public BoxRenderer() {
        //setScrollable(false);
        imNormal = Functions.getIcon("m_normal.png");
        imDeleted = Functions.getIcon("m_deleted.png");
        imRead = Functions.getIcon("m_opened.png");
        imAnswered = Functions.getIcon("m_answered.png");
        imSent = Functions.getIcon("m_sent.png");
        imFailedSent = Functions.getIcon("m_failed_send.png");
        imAttch = Functions.getIcon("m_attachment.png");
        imFlagged = Functions.getIcon("m_flagged.png");
        imRoot = Functions.getIcon("m_root.png");

        setLayout(lcduilwuit.Display.boxLayout_Y);

        Container top = new Container(new BorderLayout());
        Container bottom = new Container(new BorderLayout());
        Style a = from.getStyle();
        a.setPadding(Component.BOTTOM, 0);
        a.setMargin(Component.BOTTOM, 0);
        from.setStyle(a);
        from.setPreferredSize(new Dimension(com.sun.lwuit.Display.getInstance().getDisplayWidth()/ 2, from.getPreferredH()));
        from.setFocusable(true);
        Style b = date.getStyle();
        b.setPadding(Component.BOTTOM, 0);
        b.setMargin(Component.BOTTOM, 0);
        date.setStyle(b);
        top.addComponent(BorderLayout.WEST, from);
        top.addComponent(BorderLayout.EAST, date);

        Style c = icon.getStyle();
        c.setPadding(Component.TOP, 0);
        c.setMargin(Component.TOP, 0);
        icon.setStyle(c);

        Style d = sub.getStyle();
        c.setPadding(Component.TOP, 0);
        c.setMargin(Component.TOP, 0);
        sub.setStyle(c);
        sub.setFocusable(true);
        sub.setTickerEnabled(true);
        bottom.addComponent(BorderLayout.WEST, icon);
        bottom.addComponent(BorderLayout.CENTER, sub);

        addComponent(top);
        addComponent(bottom);

        Style s = getStyle();

        s.setBorder(Border.createLineBorder(1));
        setStyle(s);

        icon.getStyle().setBgTransparency(0);
        from.getStyle().setBgTransparency(0);
        sub.getStyle().setBgTransparency(0);
        date.getStyle().setBgTransparency(0);

    }

    public void selectionChanged(int oldSelected, int newSelected) {
    }
    private int subPosition=0;
    private int fromPosition=0;

    public void incrementPosition() {
        subPosition -= 5;
        fromPosition -= 5;
    }
    public void resetPosition()
    {
         subPosition = 0;
         fromPosition=0;
    }

    public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected) {

        MessageHeader mail = (MessageHeader) value;
        final int IMG_WIDTH=24,IMG_HEIGHT=16;
        Image img = Image.createImage(IMG_WIDTH, IMG_HEIGHT);
        // img = img.modifyAlpha((byte)0, 0xFFFFFF);
        // RGBImage rgbImg = new RGBImage(new int[16*16],16,16);

        //Image img=rgbImg.modifyAlpha((byte)0);
        Graphics g = img.getGraphics();
        g.setColor(getStyle().getBgColor());
        g.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);

        // g.setAlpha(0);
        // g.setColor(0xFF0000);
        //g.fillRect(0, 0, img.getWidth(), img.getHeight());
        int x = 1, y = 0;

        drawIcons(mail, g, x, y);
        x += 12;
        if (!mail.isPlain()) {
            g.drawImage(imAttch, x - 3, y + 3);
            x += 4;
        }
        if (mail.isFlaged()) {
            g.drawImage(imFlagged, x - 3, y);
            x += 12;
        }
        icon.setIcon(img);
        //int indexOfat = mail.getFrom().indexOf('@');
        int indexOfSpace = mail.getFrom().indexOf(" <");
        if (indexOfSpace != -1) {
            from.setText(mail.getFrom().substring(0, indexOfSpace));
        } else {
            from.setText(mail.getFrom());
        }
        String subj = mail.getSubject().length() == 0 ? Lang.get(Lang.TB_NO_SUBJECT) : mail.getSubject();
        sub.setText(subj);
        if (list.hasFocus()&& isSelected) {//hasFocus()) {
            int fromWidth=from.getStyle().getFont().stringWidth(from.getText());
            int subWidth=sub.getStyle().getFont().stringWidth(sub.getText());
            if(fromWidth>from.getWidth())
                from.setShiftText(fromPosition);
             if(subWidth>sub.getWidth())
                 sub.setShiftText(subPosition);

            if(fromWidth+fromPosition<0)
            {
               fromPosition = from.getWidth();
            }
            if(subWidth+subPosition<0)
            {
              subPosition = sub.getWidth();
            }
            sub.setEndsWith3Points(false);
            from.setEndsWith3Points(false);
        } else {
            from.setShiftText(0);
            sub.setShiftText(0);
            if (DEBUG) System.out.println("RESETING TEXT: "+sub.getText());
             sub.setEndsWith3Points(true);
            from.setEndsWith3Points(true);
        }




        String datetime = "";
        if (System.currentTimeMillis() / 86400000 == mail.getTime() / 86400000) {
            datetime = /* Lang.get(Lang.ML_TIME) + " " +*/ mail.getShortTimeStr();
        } else {
            datetime =/*Lang.get(Lang.ML_TIME) + " " + */ mail.getTimeStr().substring(5, 11);
        }
        date.setText(datetime);







        return this;


    }

    public Component getListFocusComponent(List list) {

        return Menu.focus;


    }

    public List createList(Vector vct, final TheBox box, final com.sun.lwuit.Command defaultCommand) {
        this.box = box;
       /* Vector vct = new Vector();
        for (int i = 0; i < box.getMessageCount(); i++) {
            MessageHeader mail = storage.getMessageAt(i);
            vct.addElement(mail);
        }*/

        if (DEBUG) System.out.print("Vector size" + vct.size());
        for (int i = 0; i < vct.size(); i++) {
            if (DEBUG) System.out.print("Element at" + i + "=" + vct.elementAt(i));
        }
        mailList = new List(vct) {

            private long tickTime = System.currentTimeMillis();
             int lastSel = -1;
            public void keyReleased(int key) {
                int gameAction = com.sun.lwuit.Display.getInstance().getGameAction(key);
                if (DEBUG) System.out.println("KEY RELEASED" + key);
                if (gameAction == com.sun.lwuit.Display.GAME_FIRE) {
                    box.actionPerformed(new com.sun.lwuit.events.ActionEvent(defaultCommand));
                } else {
                    super.keyReleased(key);
                }
            }

            public boolean animate() {
                if (DEBUG) System.out.println("ANIMATING BOXXXXX   LISTTTTTTTTTTTTTTTTTTTT");

                boolean val = super.animate();
                if (hasFocus()) {
                    if (DEBUG) System.out.println("HAS FOCUS");
                    long currentTime = System.currentTimeMillis();
                   
                    if (currentTime - tickTime > 100) {
                        if (lastSel == getSelectedIndex()) {
                            if (DEBUG) System.out.println("INCREMENTINGGGGG");
                            incrementPosition();
                        } else {
                        if (DEBUG) System.out.println("RESETTINGGGGGG");
                            lastSel = getSelectedIndex();
                            resetPosition();
                        }
                        tickTime=System.currentTimeMillis();
                        return true;
                    }
                }
                else{
                    if (DEBUG) System.out.println("NO FOCUS");
                }
                return val;



            }
        };


        mailList.getStyle().setBgTransparency(0);
        mailList.setListCellRenderer(this);
        mailList.setOrientation(List.VERTICAL);
        mailList.setItemGap(1);
        mailList.setBorderGap(1);
        Style s = mailList.getStyle();
        //s.setPadding(0, 0, 0, 0);
        //s.setMargin(0, 0, 0, 0);
        s.setBorder(Border.createLineBorder(1));
        mailList.setStyle(s);
        mailList.setPaintFocusBehindList(false);
        mailList.setFixedSelection(List.FIXED_NONE_CYCLIC);
        return mailList;
    }

    public List getList() {
        return mailList;
    }

    protected void drawIcons(MessageHeader mail, Graphics g, int x, int y) {
        if (mail.isEmpty()) {
            g.drawImage(imRoot, x, y + 3);//, Graphics.TOP | Graphics.LEFT );
        } else if (mail.getSendStatus() == MessageHeader.REPLIED) {
            g.drawImage(imAnswered, x, y + 3);//, Graphics.TOP | Graphics.LEFT);
        } else if (mail.getSendStatus() == MessageHeader.FAILED_TO_SEND) {
            g.drawImage(imFailedSent, x, y + 3);//, Graphics.TOP | Graphics.LEFT);
        } else if (mail.getSendStatus() == MessageHeader.SENT) {
            g.drawImage(imSent, x, y + 3);//, Graphics.TOP | Graphics.LEFT);
        } else if (mail.wasRead()) {
            g.drawImage(imRead, x, y + 3);//, Graphics.TOP | Graphics.LEFT);
        } else {
            g.drawImage(imNormal, x, y + 3);//, Graphics.TOP | Graphics.LEFT);
        }
        if (mail.wasDeleted()) {
            g.drawImage(imDeleted, x, y + 3);//, Graphics.TOP | Graphics.LEFT);
        }
    }
}
